package com.example.api.exception;

import com.example.common.api.ResultUtil;
import jakarta.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.support.WebExchangeBindException;
import org.springframework.web.server.ServerWebInputException;

@RestControllerAdvice
public class MyExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    // 统一请求的Validated验证
    @ExceptionHandler(value = {WebExchangeBindException.class})
    public ResultUtil validExceptionHandler(WebExchangeBindException bindException){
        ObjectError error = bindException.getBindingResult().getAllErrors().get(0);
        logger.error("验证错误信息：{}", error.getDefaultMessage());
        return ResultUtil.validateFailed(error.getDefaultMessage());
    }

    // 统一请求的Validated验证
    @ExceptionHandler(value = {ServerWebInputException.class})
    public ResultUtil validExceptionHandler(ServerWebInputException exception){
        logger.error("传入的参数有误：{}", exception.getMessage());
        return ResultUtil.validateFailed("缺少传参：" + exception.getMethodParameter());
    }

    // 统一请求的Validated验证
    @ExceptionHandler(value = {ConstraintViolationException.class})
    public ResultUtil validExceptionHandler(ConstraintViolationException exception){
        logger.error("验证错误信息：{}", exception.getMessage());
        return ResultUtil.validateFailed(exception.getMessage());
    }

    // 报错信息
    @ExceptionHandler(value = {Exception.class})
    public ResultUtil errorExceptionHandler(Exception exception){
        logger.error("报错信息：{}", exception.getClass() + "==>>" + exception.getMessage());
        return ResultUtil.validateFailed(exception.getMessage());
    }
}
